package com.android.lovely.ui.dialog

import com.android.lovely.R
import com.android.lovely.aav.PreferentialManager
import com.android.lovely.api.service.userService
import com.android.lovely.data.PayDetail
import com.android.lovely.data.SubPreferential
import com.android.lovely.databinding.DialogPersuasionBinding
import com.android.lovely.framework.BaseDialogFragment
import com.android.lovely.framework.launchWithLoading
import com.android.lovely.user.UserManager
import com.kotlin.extensions.view.ViewExt.clickable
import io.glassfy.androidsdk.GooglePlayManager
import io.glassfy.androidsdk.model.PurchaseParams

class PersuasionDialog : BaseDialogFragment<DialogPersuasionBinding>() {
    override fun initializeViews() {
        isCancelable = false
        val info = PreferentialManager.product
        val subActive = PreferentialManager.firstActive
        if (!PreferentialManager.isEnable || info == null || subActive == null) {
            dismiss()
            return
        }
        binding.free.text = getString(R.string.gems_for_free,subActive.giftNum)
        binding.giveUp.clickable { dismissAllowingStateLoss() }
        binding.get.clickable {
            buyPreferential(subActive, info)
        }
    }

    private fun buyPreferential(subPreferential: SubPreferential, product: PayDetail) {
        viewLifecycleScope.launchWithLoading {
            userService.reportPerferential(
                mapOf(
                    "act_id" to subPreferential.id,
                    "product_list" to subPreferential.productList.joinToString(",") { it.id.toString() })
            )
            val isSuccess = GooglePlayManager.purchase(requireActivity(), product.appleId, PurchaseParams(UserManager.authId.toString(), product.price.toFloat()))
            if (isSuccess) {
                PreferentialManager.init()
                runCatching { dismissAllowingStateLoss() }
            }
        }
    }
}